<template>
  <div>
    <el-card>
      <div class="mb-4">
        <el-button type="primary" @click="handleAddLeave">新增请假</el-button>
      </div>
      <el-table :data="leaveList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户">
          <template #default="{ row }">
            {{ userFormatter(row.userId) }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始时间">
          <template #default="{ row }">
            {{ formatDateTime(row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束时间">
          <template #default="{ row }">
            {{ formatDateTime(row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="请假原因" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            {{ statusText(row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="handleEditLeave(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteLeave(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户">
            <el-option 
              v-for="user in userMap" 
              :key="user.id" 
              :label="user.userName" 
              :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker 
            v-model="form.startDate" 
            type="datetime" 
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker 
            v-model="form.endDate" 
            type="datetime" 
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="请假原因" prop="reason">
          <el-input v-model="form.reason" placeholder="请输入请假原因" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="待审批" :value="0" />
            <el-option label="已批准" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitLeaveForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 修改导入名与实际函数名一致
import { listLeaveapplication, addLeaveapplication, updateLeaveapplication, delLeaveapplication } from '@/api/leaveapplication'
import { listUsertable } from '@/api/usertable'

const leaveList = ref([])
const userMap = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref(null)

const form = reactive({
  id: null,
  userId: null,
  startDate: '',
  endDate: '',
  reason: '',
  status: null
})

const rules = {
  userId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  reason: [{ required: true, message: '请输入请假原因', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 状态文本转换
const statusText = (type) => {
  const map = {
    0: '待审批',
    1: '已批准',
    2: '已拒绝'
  }
  return map[type] || '未知'
}

// 格式化日期时间函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toISOString().split('T')[0] + ' ' + date.toTimeString().split(' ')[0];
}

// 获取请假记录列表
const getLeaveList = async () => {
  try {
    const response = await listLeaveapplication();
    if (response) {
      leaveList.value = response;
    } else {
      ElMessage.error('获取请假列表失败: 数据格式异常');
    }
  } catch (error) {
    ElMessage.error(`获取请假列表失败: ${error.message}`);
  }
}

// 新增请假记录
const handleAddLeave = () => {
  dialogTitle.value = '新增请假'
  isAdd.value = true
  Object.assign(form, {
    id: null,
    userId: null,
    startDate: '',
    endDate: '',
    reason: '',
    status: null
  })
  dialogVisible.value = true
}

// 编辑请假记录
const handleEditLeave = (row) => {
  dialogTitle.value = '编辑请假'
  isAdd.value = false
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除请假记录
const handleDeleteLeave = (row) => {
  ElMessageBox.confirm('确认删除该请假记录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delLeaveapplication(row.id);
    ElMessage.success('删除成功');
    getLeaveList();
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

// 提交请假表单
const submitLeaveForm = async () => {
  await formRef.value.validate();
  try {
    if (isAdd.value) {
      await addLeaveapplication(form);
      ElMessage.success('新增成功');
    } else {
      await updateLeaveapplication(form);
      ElMessage.success('更新成功');
    }
    dialogVisible.value = false;
    getLeaveList();
  } catch (error) {
    ElMessage.error('操作失败');
  }
}

// 用户ID转名称
const userFormatter = (value) => {
  const user = userMap.value.find((item) => item.id == value)
  return user ? user.userName : value
}

// 获取用户数据
const fetchUsers = async () => {
  try {
    const response = await listUsertable({ roleId: 3 }); // 可按需添加筛选条件
    if (response) {
      userMap.value = response;
    }
  } catch (error) {
    console.error('获取用户列表错误:', error);
  }
}

onMounted(() => {
  getLeaveList();
  fetchUsers();
})
</script>